import { gltfWithDracoLoder } from './gltfWithDracoLoader.js'

import { AnimationMixer } from 'three'

function setupModel(data,autoPlayAnimations) {
  console.log('gltf data:', data)
  const model = data.scene
  if (data.animations[0]) {
    const clips = data.animations
    model.animations = clips;
    const mixer = new AnimationMixer(model)
    //const action=mixer.clipAction(clip);
    //action.play();
    //播放全部动画
    if(autoPlayAnimations){
      autoPlayAnimations.forEach(animName => {
        clips.forEach(clip => {
          if(clip.name == animName){
            mixer.clipAction(clip).play()
          }
        })
      })
    }else{
      clips.forEach(clip => {
        mixer.clipAction(clip).play()
      })
    }

    model.mixer = mixer;

    model.tick = (delta) => {
      mixer.update(delta)
    }
  }
  return model
}

var firstTime = true

async function asyncLoadGLTF(gltfUrl, autoPlayAnimations) {
  const { loader, dracoLoader } = gltfWithDracoLoder()
  let [gltfData] = await Promise.all([
    loader.loadAsync(gltfUrl, (xhr) => {
      // console.log((xhr.loaded / xhr.total) * 100 + '% loaded')
    })
  ])
  let mesh = setupModel(gltfData,autoPlayAnimations)
  console.log('load done:', mesh)
  dracoLoader.dispose()
  return mesh
}
async function asyncLoadGLTFData(gltfUrl, callback) {
  const { loader, dracoLoader } = gltfWithDracoLoder()

  let [gltfData] = await Promise.all([
    loader.loadAsync(gltfUrl, (xhr) => {
      // console.log((xhr.loaded / xhr.total) * 100 + '% loaded')
      callback((xhr.loaded / xhr.total) * 100)
    })
  ])

  dracoLoader.dispose()
  return gltfData
}

export { asyncLoadGLTF, setupModel, asyncLoadGLTFData }
